// pages/share/share.js
let that,
  api = new (require('../../utils/api.js')),
  util = new (require('../../utils/util.js')),
  //imghead = api.getimgurl(),
  imghead = 'https://www.jihemu.com/bookapi/imgs/',
  videohead = 'https://www.jihemu.com/bookapi/myvideo/',
  audiohead = 'https://www.jihemu.com/bookapi/myaudio/',
  myaudio = wx.createInnerAudioContext(),
  app = getApp(); 

Page({

  /**
   * 页面的初始数据
   */
  data: {
    addshow:!1,
    genzong:'',
    noteshow:!0,
    videohead,
    keyword:'',
    sel_phone:'',
    genzongshow:!1,
    sel_keypwd:'',
    pool: 'BJ',
    addaddress:!1,
    imghead,
    top: [
      {
        name: '跟踪',
        value: 'BJ'
      },
      {
      name: '签单',
      value: 'QD'
    },
    {
      name: '设计',
      value: 'SJ',
    },
    {
      name: '下单',
      value: 'XD',
    },
    {
      name: '施工',
      value: 'SG',
    },
    {
      name: '售后',
      value: 'SH',
    },
    ],
    clickgood: !0,
    isCollect: false,
    currentTab: 0,
    currentageindex: -1,
    currentpage: 1,
    list: [],
    genzongword:'',
    name:'',
    phone:'',
    needupdate: !1,
    hideadd: !0,
    commontarr: [],
    isfollow: '',
    // followidsarr:[],
    hasphone: !1,
    sendshow: !1,
    isplay: !1,
    pagesize: 15,
    start: 0,
    audioid: 0,
    showRegister: !1,
    kindname: '',//幼儿园名称
    classname: '',//班级名称
    babyname: '',//宝宝姓名
    selid:0,
    testlat:'27.144317',
    testlng:'114.994954'
  },

  selitem(e){
    let{id,name}= e.currentTarget.dataset,{selid} = this.data
    that.setData({selid:selid==id?0:id,selname:name})
  },

  add_input(e){
    let{code} = e.currentTarget.dataset,{value} = e.detail
    that.setData({[code]:value})
  },

  tonav(e) {
 
    let {sel_locationdata} = this.data
    console.log(sel_locationdata,'sel_locationdata');
    let plugin = requirePlugin('routePlan');
    let key = 'TVXBZ-AIGKL-4PTPP-MEOKG-KQYB2-PRFEY';  //使用在腾讯位置服务申请的key
    let referer = '路线规划';   //调用插件的app的名称
    let endPoint = JSON.stringify({  //终点

      'name':sel_locationdata.name ,//e.currentTarget.dataset.address,
      'latitude': parseFloat(sel_locationdata.latitude),
      'longitude': parseFloat(sel_locationdata.longitude)
    });
    wx.navigateTo({
      url: 'plugin://routePlan/index?key=' + key + '&referer=' + referer + '&endPoint=' + endPoint + '&navigation=1'
    });
  },

  search(e){
    this.setData({keyword:e.detail.value})
  },
  goup(e){
    let{up} = e.currentTarget.dataset,{ selid}=this.data 
    if(selid>0){
      api.share_upordown({id:selid,up},res=>{
        if(res.data.issuccess==1){
          that.gosearch()
        }
      })
    }
  },

  wangong(){
    let {  selid } = this.data,that = this
    wx.showLoading({
      title: '加载中',
    })
    if(selid>0){
      let item = this.data.list.find(x=>{return x.id==selid})
      console.log(item,'itemtiem');
      if(item.finished=='0'){
 api.完工(selid,res=>{
        wx.hideLoading()
        if(res.data.issuccess==1){
          that.gosearch()
          that.setData({selid:0})
        }
      })
      }else{
        wx.hideLoading()
        wx.showToast({
          title: '该地址已完工',
        })
      }
      // wx.navigateTo({
      //   url: '../daka/daka?id='+selid+'&n='+selname,
      // })
    }else{
      wx.showToast({
        title: '请先选择地址',
      })
    }
  },

  gosearch(){
    this.setData({list:[],start:0},()=>{
      that.getlist()
    })
  }, 
  togenzong(e){
  let{id,note} = e.currentTarget.dataset;
  this.setData({genzongid:id,genzong:note,genzongshow:!0})
  },

daka(){
  let {  selid,selname } = this.data
    if(selid>0){
      wx.navigateTo({
        url: '../daka/daka?id='+selid+'&n='+selname,
      })
    }else{
      wx.showToast({
        title: '请先选择地址',
      })
    }
},

  del(e){
    let {  selid } = this.data
    if(selid>0){
      wx.showModal({
        title: '提示',
        content: '确定要删除吗',
        complete: (res) => {
          if (res.cancel) {
          }
          if (res.confirm) {
            api.share_del(selid,res=>{
              if(res.data.issuccess==1){
                that.gosearch()
              }else{
                wx.showToast({
                  title: res.data.msg,
                })
              }
            })  
          }
        }
      })
    }else{
      wx.showToast({
        title: '请先选择地址',
      })
    }


   
  },

  zhuanru(e){
    let {  selid } = this.data
    if(selid>0){
      let{code}=e.currentTarget.dataset,{value} = e.detail
      api.share_zhuanru({id:selid,pool:code,date:new Date(value).getTime()/1000},res=>{
        if(res.data.issuccess==1){
          that.gosearch()
        }else{
          wx.showToast({
            title: res.data.msg,
          }) 
        }
      })
    }else{
      wx.showToast({
        title: '请先选择地址',
      })
    }


 
   

  },


  settop(e){

    let {  selid } = this.data
    if(selid>0){
    wx.showModal({
      title: '提示',
      content: '请确定操作',
      complete: (res) => {
        if (res.cancel) {
        }
        if (res.confirm) {
          api.share_settop(selid,res=>{
            if(res.data.issuccess==1){
              that.gosearch()
            }else{
              wx.showToast({
                title: res.data.msg,
              })
            }
          })  
        }
      }
    })
    }else{
      wx.showToast({
        title: '请先选择地址',
      })
    }



  },

  getfavorlist() {
    let { KindergartenData, kindname, classname, babyname } = that.data
    api.getKindergarten(res => {
      if (res.data.issuccess == 1) {
        KindergartenData = res.data.data 
        if (KindergartenData) {
          kindname = KindergartenData.kindname
          babyname = KindergartenData.babyname
          classname = KindergartenData.classname
        }
        that.setData({ KindergartenData, kindname, classname, babyname })
      }
    })
    api.getfavorlist(res => {
      if (res.data.issuccess = 1) {
        let favorlist = res.data.list;
        let {
          currentageindex
        } = this.data;
        this.setData({
          favorlist
        }, that.getlist(currentageindex, 0));
      }
    });
  },
  /**getPhoneNumber
    * 生命周期函数--监听页面加载
    */
  onLoad: function (options) {
    that = this;
    if (app.logininfo) {
      console.log('herere');
      that.getdata(); 
    } else {
      util.setwatcher(app, that.afterlogin)
    }
  },
  afterlogin: {
    logininfo: res => {
      // let logininfo = app.logininfo
      // that.setData({ myid: logininfo.userid})
      // console.log(app.logininfo,'logininfo');
      // console.log('afterlogin fen');
      that.getdata();
    }
  },
  getPhoneNumber(e) {
    let { hasphone, sendshow } = that.data
    api.getphone({ edata: e.detail.encryptedData, iv: e.detail.iv }, res => {
      if (res.data.issuccess == 1) {
        let data = JSON.parse(res.data.data);
        let isgetphone = true
        wx.setStorageSync('isgetphone', isgetphone)
        that.setData({ hasphone: !0, sendshow: !1, isgetphone })
        console.log(data, 'data')
        //更新用户手机号
        api.bindphone(data.phoneNumber, res => {
          if (res.data.issuccess == 1) {
            console.log(res.data, 'phone')
            that.getlist()
          }
        })
      }
    })
  },

  tofollow(e) {
    let { id, isfollow } = e.currentTarget.dataset, { followids, followidsarr, list, currentageindex } = that.data
    if (isfollow == 1) {
      api.setfollow(id, res => {
        if (res.data.issuccess == 1) {
          that.setData({ list: [] })
          that.getlist(currentageindex, 0)
          wx.showToast({
            title: res.data.isfollow,
            icon: 'none'
          })

        }
      })
    } else {
      api.setfollow(id, res => {
        if (res.data.issuccess == 1) {
          that.setData({ list: [] })
          that.getlist(currentageindex, 0)
          wx.showToast({
            title: res.data.isfollow,
            icon: 'none'
          })
        }
      })
    }
  },
  toperson(e) {
    wx.navigateTo({
      url: '../person/person?id=' + e.currentTarget.dataset.id,
    })
  },
  toggle(e) {
    let {
      list
    } = this.data, {
      index
    } = e.target.dataset;
    console.log(index, list, "1254545", e);
    list[index].ellipsis = !list[index].ellipsis;
    this.setData({
      list
    })
  },


  //播放音频
  playaudio(e) {
    let { src, duration, isplay1, id } = e.currentTarget.dataset, { audioid, list } = that.data
    list.forEach(x => {
      if (e.currentTarget.dataset.id == x.item.id) {
        if (!x.isplay1) {
          x.isplay1 = !0
        }
        that.setData({ list })
      }
    })
    if (myaudio.src == audiohead + src) {
      myaudio.stop()
      myaudio.play()
      return
    }
    myaudio.src = audiohead + src
    myaudio.play()

  },
  // getlist(currentageindex, start) {
  //   let { pagesize,list } = this.data, subdata = {start,pagesize, condition: currentageindex },piclist=[];
  //   api.getcommentlist(subdata, res => {
  //     if (res.data.issuccess == 1) {
  //       this.setData({
  //         length: res.data.list.length,
  //         list
  //       });
  //       this.formatdata(res.data.list);
  //     } else {
  //     }
  //   });
  // },
  formatdata(clist) {
    let {
      favorlist,
      list, followidsarr
    } = this.data, piclist = [];
    clist.forEach((y, j) => {
      clist[j]["ellipsis"] = !1;
      clist[j]["favor"] = clist[j].item["favor"];
      clist[j].item["username"] = clist[j].item["username"] || '匿名用户' + clist[j].item.userid;
      clist[j]["isshow"] = !1;
      if (y.item.contents) {
        clist[j]["wordcount"] = y.item.contents.length;
      }
      if (favorlist.indexOf(String(y.item.id)) != -1) {
        clist[j]["isfavor"] = !0;
      } else {
        clist[j]["isfavor"] = !1;
      }
    })
    clist.forEach((x, i) => {
      x.item.updateDate = util.formatTime(new Date(x.item.updateTime))
      x['isplay'] = !1
      if (x.item.piclist != null && x.item.piclist != '') {
        piclist = x.item.piclist.split(',')
        piclist.forEach((y, i) => {
          piclist[i] = y.replace('imgs/', '')
        });
        x.piclist = piclist;
      }
      list.push(x)
    });
    this.setData({
      list
    }, () => {
      that.getheight()
    });
  },
  getheight() {
    let { list } = that.data
    let query = wx.createSelectorQuery().in(this);
    query.selectAll('.content').boundingClientRect().exec(res => {
      console.log(res, 'resres')
      let lineHeight = 25; //固定高度值 单位：PX
      for (var i = 0; i < res[0].length; i++) {
        if ((res[0][i].height / lineHeight) > 3) {
          console.log(res[0][i].height, 'res[0][i].height ');
          list[i]["ellipsis"] = !0;
          list[i]["isshow"] = !0
        }
      }
      that.setData({
        list
      })
    });
  },
  tolocation(){
    wx.chooseLocation({
      success:res=>{
        let{name,address,latitude,longitude}=res
        console.log(res,'success');
        that.setData({sel_locationdata:
         {name:name+address,latitude,longitude}
        //{}
        })
      },
      complete:res=>{
        
      }
    })
  },
  toadd() {
    // wx.navigateTo({
    //   url: '../shareadd/shareadd',
    // })

  
      
    
   this.setData({addshow:!0})


  },
  hideaddshow(){
    this.setData({addshow:!1})
  },
  hideaddressshow(){
    this.setData({addaddress:!1})
  },
  descinput(e){
    let{id} = e.currentTarget.dataset
    console.log(e,'eee');
    this.setData({selid:id, descinput:e.detail.value})
  },
  descedit(e){
    let{id} =e.currentTarget.dataset, { descinput,selid } = this.data;
    console.log({id,descinput},'descedit');
    if(selid>0){
   api.share_genzong({id:selid,note:descinput},res=>{
      if(res.data.issuccess==1){
        that.setData({selid:0},()=>{   
         // that.getlist()
        })
      }
    })
    }

 


    //this.setData({descinput:e.detail.value})
  },

  tabtap(e) {
   
    let { index } = e.currentTarget.dataset, { currentageindex, top } = this.data;
    if (index == currentageindex) {
      return;
    }
    this.setData({
      list:[],
      pool: top[index].value,
      currentageindex: index,
      start: 0,
    }, () => {
      this.getlist()
    })

    //  this.getlist(index, 0);
  },
  delcom(e) {
    let {
      id,
      index
    } = e.target.dataset, {
      list
    } = this.data;
    wx.showModal({
      title: '提示',
      content: '确定删除吗？',
      success: function (res) {
        if (res.confirm) {
          api.delcomment(id, res => {
            if (res.data.issuccess == 1) {
              console.log(res, "成功删除");
              list.splice(index, 1);
              that.setData({
                list
              });
            }
          })
        }
      }
    })
  },
  toGood(e) {
    console.log(e, 'toGood')
    // this.setData({
    //   clickgood: !1
    // });
    // let {favor,id,isfavor,index} = e.currentTarget.dataset, { list } = this.data,title=isfavor?'取消点赞':'点赞成功';
    // favor = Number(favor);
    // console.log(list[index],'list[index]');
    // list[index]['isfavor'] = isfavor ? !1 : !0;
    // list[index]['favor'] = isfavor ? favor - 1 : favor + 1;
    // api.dofavor(id, res => {
    //   if (res.data.issuccess == 1) {
    //     that.setData({list})
    //     wx.showToast({
    //       title,
    //     })
    //   }
    // })
    // setTimeout(function() {
    //   that.setData({
    //     clickgood: !0
    //   })
    // }, 2000);

    let { id, islike } = e.currentTarget.dataset, { currentageindex, list } = that.data
    if (islike == '0') {
      api.dofavor(id, res => {
        if (res.data.issuccess == 1) {
          list.forEach(x => {
            if (x.item.id == id) {
              x['islike'] = 1
              x['item']['favor'] = x.item.favor + 1
            }
          })

          that.setData({ list })
          // that.getlist(currentageindex, 0) 
          wx.showToast({
            title: '点赞成功',
            icon: 'none'
          })
        }
      })
    } else {
      api.dofavor(id, res => {
        if (res.data.issuccess == 1) {
          list.forEach(x => {
            if (x.item.id == id) {
              x['islike'] = 0
              x['item']['favor'] = x.item.favor - 1 
              // x['favor']=x.favor-1
            }
          })

          that.setData({ list })
          // that.getlist(currentageindex, 0) 
          wx.showToast({
            title: '取消成功',
            icon: 'none'
          })
        }
      })
    }

  },
  previewimg(e) {
    let {
      imghead
    } = this.data, {
      index,
      arr,
      img
    } = e.currentTarget.dataset;
    let myarr = [];
    arr.forEach((v, i) => {
      myarr.push(imghead + v)
    })
    console.log(myarr, 'myarr');
    wx.previewImage({
      urls: myarr,
      current: imghead + img
    })
  },
  getdata() {
   
    let userinfo = app.logininfo.user, { pagesize, start } = this.data
    console.log(app.logininfo,'app.logininfo');
    that.setData({ sendshow: userinfo['phone'] == null, hasphone: userinfo.phone != null })
    console.log(userinfo, 'fff');
    this.getlist()
  },

  getlist() {
    wx.showLoading({
      title: '加载中',
    })
    let { pagesize, start, pool ,keyword} = this.data
    api.share_getlist({ pagesize, start, pool,keyword }, res => { 
      wx.hideLoading()
      let { list,total,list1 } = res.data
    
      list.forEach(x => { 
        x['date'] = util.formatDate(new Date(x.updateDate))
      })
      list1.forEach(x => { 
        x['date'] = util.formatDate(new Date(x.updateDate))
      })
      let l =that.data.list.concat(list)
      let l1 = [],l2=[]
      // l.forEach(x=>{
      //   if(x.finished=='1'){
      //     l2.push(x) 
      //   } else{
      //     l1.push(x)
      //   }
      // })
     // console.log({l2,l1},'lll');
        // l.sort(x=>{
        //   return Number(x.finished)>0
        // })


      console.log(l,'listlist--getlist');
      that.setData({ list:l.concat(list1),total })
    })
  },


  inputtap(e) {
    let { prop } = e.target.dataset, { value } = e.detail
    that.setData({ [prop]: value })
  },
  inputgz(e) {
    let { value } = e.detail
    that.setData({ genzong: value })
  },

  qdaddress(){
     let{selid,sel_note,sel_phone,sel_keypwd,sel_locationdata} = this.data,err='';
    //  if(selid){err='请输入跟踪信息'}
    console.log(sel_phone,'sel_phone');
    if(sel_note==''){err='请输入地址'}
    if(sel_phone.length!=11){err='电话号码输入有误'}  
    if(!sel_locationdata){err='请选择区域'}
    if(err!=''){
      wx.showToast({
        title: err,
        icon:'none'
      })
    }else{
      let  {name,latitude,longitude} =sel_locationdata, 
       data = {id:selid,note:sel_note,keypwd:sel_keypwd,phone:sel_phone,address:name,lat:latitude,lng:longitude}
      api.share_setaddress(data,res=>{
        if(res.data.issuccess==1){
          that.setData({addaddress:!1, list:[]},()=>{
            that.getlist()
          })
        }else{
          wx.showToast({
            title: res.data.msg,
            icon:'none'
          })
        }
      })

    }
  },
 
  qdadd(){
   
    let{desc,name,phone,pool} = this.data,err = ''; 
    if(desc==''){err='请输入跟踪信息'}
    if(name==''){err='请输入名称'}
    if(phone.length!=11){err='电话号码输入有误'}  
    if(err!=''){
      wx.showToast({
        title: err,
        icon:'none'
      })
    }else{
     
      api.share_add({name,phone,_desc:desc,pool},res=>{
        if(res.data.issuccess==1){
          this.setData({addshow:!1})
          that.setData({list:[]},()=>{
            that.getlist()
          })
        }else{
          wx.showToast({
            title: res.data.msg,
            icon:'none'
          })
        }
      })
    }
  },


  qdgenzong(){
    this.setData({genzongshow:!1})
    let{genzong,genzongid} = this.data;
    if(genzong==''){
      wx.showToast({
        title: '跟踪情况不能空',
      })
    }else{
      api.share_genzong({id:genzongid,note:genzong},res=>{
        if(res.data.issuccess==1){
          that.setData({list:[]},()=>{
            that.getlist()
          })
        }
      })
    }
  },
  register() {
    let { kindname, classname, babyname, KindergartenData } = that.data, err = ''
    if (babyname == '') err = '请输入宝宝姓名'
    if (classname == '') err = '请输入班级名称'
    if (kindname == '') err = '请输入幼儿园名称'
    if (err.length > 0) {
      wx.showToast({
        title: err,
        icon: 'none'
      })
      return
    }
    wx.showLoading({
      title: '登记中...',
    })
    api.aoeKindergarten({ kindname, classname, babyname }, res => {
      wx.hideLoading()
      if (res.data.issuccess == 1) {
        wx.showModal({
          title: '提示',
          content: "登记成功",
          showCancel: !1,
          success(res) {
            if (res.confirm) {
              api.getKindergarten(res => {
                if (res.data.issuccess == 1) {
                  KindergartenData = res.data.data
                  that.setData({ KindergartenData })
                }
              })
            }
          }
        })
        that.setData({ showRegister: !1 })
      }
    })
  },
  /**
   * 跳转评论详情页
   */
  skip(e) {
    console.log(111, '11')
    let { isgetphone } = that.data
    // that.setData({sendshow:!0})
    if (!isgetphone) {
      that.setData({ sendshow: !0 })
    } else {
      wx.navigateTo({
        url: '../sharedetail/sharedetail?id=' + e.currentTarget.dataset.id,
      })
    }
  },


  no() {
    that.setData({ sendshow: !1 })
  },
  tolisten() {
    console.log(22222);
    wx.switchTab({
      url: '../answer/answer',
    })
  },
  tobank() {
    wx.navigateTo({
      url: '../days/days',
    })
  },
  showRegister() {
    wx.navigateTo({
      url: '../registration/registration',
    })
    // that.setData({showRegister:!0})
  },
  closeRegister() {
    that.setData({ showRegister: !1 })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let isgetphone = wx.getStorageSync('isgetphone')
    if (isgetphone) {
      that.setData({ isgetphone, hasphone: !0, sendshow: !1 })
    }
    if (this.data.needupdate) {
      let {
        currentageindex
      } = this.data;
      that.setData({
        currentpage: 1,
        list: [],
        needupdate: !1,
        currentageindex: 1,
      }, () => {
        console.log('needupdate fen');

        that.getfavorlist();
      });
    }

  },
  showaddress(){
    let {  selid } = this.data
    if(selid>0){
      let {list} = this.data ,item = list.find(x=>{return x.id==selid})
      console.log(item,'showaddress');
      that.setData({addaddress:!0,sel_locationdata:{name:item.address,latitude:item.lat,longitude:item.lng}, sel_keypwd:item.keypwd, sel_note:item.note,sel_phone:item.phone||''})

    }else{
      wx.showToast({
        title: '请先选择地址',
      })
    }
    
  },

  setaddress(e) {
    let {  selid } = this.data
    if(selid>0){
     

    }else{
      wx.showToast({
        title: '请先选择地址',
      })
    }
    
  },


  todetail(e) {
    let {  selid } = this.data
    if(selid>0){
      wx.navigateTo({
        url: '../sampleReelsDetail/sampleReelsDetail?id=' + selid,
      })
    }else{
      wx.showToast({
        title: '请先选择地址',
      })
    }
    
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let {list, total,start,pagesize} = this.data;
    if (total == list.length) {
      wx.showToast({
        icon: "none",
        title: '再怎么扯也没有了',
      })
      return;
    }else{
      this.setData({start:start+pagesize},res=>{
        that.getlist()
      })
    }
    // start = pagesize * currentpage;
    // currentpage = currentpage + 1;
    // this.setData({
    //   start,
    //   currentpage
    // });
    // this.getlist(currentageindex, start);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    console.log(e,'eeee');
    if(e.from=='button'){
      let {selname,selid} = that.data
      return {
        title: selname,
        path: `pages/addressshare/addressshare?id=`+selid,
      }
    }else{
      return {
        title: app.logininfo.appletname,
        path: `pages/share/share?share=` + app.logininfo.userid,
      }
    }
   
  }
})